#coding=utf-8
import os
from config import config

def filename_change(filename):
	import time
	import md5
	f = md5.md5(str(time.time()))
	return f.hexdigest() + "." + filename.rsplit('.', 1)[1]

def allowed_file(filename):
	return '.' in filename and \
		filename.rsplit('.', 1)[1] in config.ALLOWED_EXTENSIONS

def img_resize(file,size):
	from PIL import Image
	img = Image.open(file)
	img = img.resize(size)
	img.save(file)
	return file

def img_upload(file, size=""):
	if allowed_file(file.filename):
		filename = filename_change(file.filename)
		path = os.path.join(config.UPLOAD_FOLDER, 'image', filename[0], filename[1], filename.rsplit('.')[1])
		if os.path.exists(path)!=True:
			os.makedirs(path)
		file.save(os.path.join(path, filename))

		if size != "":
			img_resize(os.path.join(path, filename), size)
		retpath = '' #config.STATIC_PATH
		retpath += os.path.join("/uploads/image/", filename[0], filename[1], filename.rsplit('.')[1], filename)
		return  retpath
	else:
		return '图片格式不正确' + str(config.ALLOWED_EXTENSIONS)
